angular.module('app.controllers', [])


  .controller('MenuCtrl', ['$rootScope', '$scope', 'AppCache', '$state', 'UserService', 'Storage', '$ionicSideMenuDelegate', '$ionicPopover', '$ionicHistory',
    function ($rootScope, $scope, AppCache, $state, UserService, Storage, $ionicSideMenuDelegate, $ionicPopover, $ionicHistory) {


      $scope.$on('$ionicView.afterEnter', function () {
        $ionicPopover.fromTemplateUrl('templates/popover.html', {
          scope: $scope,
        }).then(function (popover) {
          $scope.popover = popover;
        });

      });

      $scope.loginOut = function () {
        $scope.popover.hide();

        UserService.doLogout();

        $state.go('signIn', {}, {reload: true});
      };
      $scope.goModifyPwd = function () {
        $scope.popover.hide();
        $state.go('modifyPwd');
      };
    }])

  /**
   * 数据初始化
   */
  .controller('LoadingCtrl', ['$scope', '$state', 'UserService', 'CommonService',
    function ($scope, $state, UserService, CommonService) {

      /**
       * 处理自动登陆相关逻辑
       */
      var processAutoLogin = function () {
        var isNeedLogin = UserService.isNeedLogin(Storage);
        if (isNeedLogin) {
          $state.go('signIn', {}, {reload: true});
        } else {
          $state.go('menu', {}, {reload: true});
        }
      };

      $scope.loadInitData = function () {
        $scope.showLoading = true;
        document.getElementById('loadingFooterBar').style.display = 'none';
        CommonService.getInitData().then(function () {
          processAutoLogin();
        }, function () {
          $scope.showLoading = false;
          document.getElementById('loadingFooterBar').style.display = 'block';
        });
      };
      $scope.$on('$ionicView.beforeEnter', function () {
        $scope.showLoading = true;
      });
      $scope.$on('$ionicView.afterEnter', function () {
        $scope.loadInitData();
      });


    }])

  /**
   * 密码修改
   */
  .controller('ModifyPwdCtrl', ['$scope', 'UserService', 'ionicToast', '$cordovaToast', '$ionicHistory',
    function ($scope, UserService, ionicToast, $cordovaToast, $ionicHistory) {
      $scope.$on('$ionicView.beforeEnter', function () {
        //表单验证提示
        $scope.newPasswordErrorTips = {
          required: '请输入新密码'
        };
        $scope.passwordErrorTips = {
          required: '请输入原密码'
        };
        $scope.confirmNewPasswordErrorTips = {
          required: '请确认密码'
        };
        $scope.user = {};
        $scope.submit = function () {

          if ($scope.user.newPassword != $scope.user.confirmNewPassword) {
            ionicToast.show('密码不匹配', 'top', false, 1000);
            return;
          }

          UserService.doModifyPwd($scope.user).then(function () {
            $cordovaToast.showShortCenter('修改成功');
            //密码修改成功后返回上一页面
            $ionicHistory.goBack();
          }, function (reason) {
            $cordovaToast.showShortCenter(reason.message);
          });
        };

      });

    }])

  .controller('SignInCtrl', ['$scope', 'UserService', 'ionicToast', '$state',   '$ionicHistory',
    function ($scope, UserService, ionicToast, $state, $ionicHistory) {

      $scope.$on('$ionicView.beforeEnter', function () {
        /**
         * 用户注销后,需要断开长连接服务器
         */


        //表单验证提示
        $scope.userNameErrorTips = {
          required: '用户名不能为空'
        };
        $scope.passwordErrorTips = {
          required: '密码不能为空'
        };

        $scope.user = {
          autoLogin: true
        };
      });
      $scope.$on('$ionicView.afterEnter', function () {

      });

      $scope.submit = function () {

        UserService.doLogin($scope.user).then(function () {
          //登陆成功,连接长连接服务器

          $ionicHistory.clearCache().then(function () {
            $state.go('menu');
          })
          //$state.go('menu', {}, {reload: true});
        }, function (reason) {
          ionicToast.show(reason.message, 'top', false, 1000)
        });

      };


    }])

  /**
   * 用户注册
   */
  .controller('SignUpCtrl', ['$scope', '$rootScope', 'ionicToast', 'UserService', '$state', '$cordovaToast',
    function ($scope, $rootScope, ionicToast, UserService, $state, $cordovaToast) {

      $scope.update = function (userType) {
        //4表示字典中的旅馆用户
        if (userType == '4') {
          $scope.includeTmpls = [
            'templates/hotelRegisterLegalPerson.html',
            'templates/hotelRegisterLbasic.html',
          ];
        } else {
          $scope.includeTmpls = [
            'templates/ordinaryRegisterBasic.html',
          ];
        }
      }

      $scope.$on('$ionicView.beforeEnter', function () {
        $scope.user = {};
        $scope.userType = {};
        $scope.includeTmpls = [];
        //旅馆照片
        $scope.hotelImages = [];

        //表单验证提示
        $scope.userTypeErrorTips = {
          required: '请选择用户类型'
        };
        $scope.userNameErrorTips = {
          required: '用户名不能为空'
        };
        $scope.passwordErrorTips = {
          required: '密码不能为空'
        };
        $scope.confirmPasswordErrorTips = {
          required: '确认密码不能为空'
        };
        $scope.ordinaryAddressErrorTips = {
          required: '请填写现住地址'
        };

        $scope.ordinaryNameErrorTips = {
          required: '请填写姓名'
        };
        $scope.ordinaryidCardNoErrorTips = {
          required: '请填写身份证号码'
        };
        $scope.legalPersonNameErrorTips = {
          required: '请填写法人姓名'
        };

        $scope.legalPersonNameErrorTips = {
          required: '请填写法人姓名'
        };
        $scope.legalPersonGenderErrorTips = {
          required: '请选择法人性别'
        };
        $scope.legalPersonIDCardNoErrorTips = {
          required: '请填写法人身份证号码'
        };
        $scope.legalPersonAddressErrorTips = {
          required: '请填写法人现住地址'
        };

        $scope.hotelNameErrorTips = {
          required: '请填写旅馆名称'
        };
        $scope.hotelSeatCountErrorTips = {
          required: '请填写旅馆床位数'
        };

        $scope.hotelAddressErrorTips = {
          required: '请填写旅馆地址'
        };

        $scope.hotelGovernOfficeErrorTips = {
          required: '请填写所在的派出所'
        };

        $scope.user = {};
      });
      $scope.$on('$ionicView.afterEnter', function () {

      });
      $scope.submit = function () {


        /**
         * 身份证验证
         */
        if ($scope.user.userType == '4') {
          var idInfo = getIdCardInfo($scope.user.legalpersonidcardno);
          if (!idInfo || !idInfo.isTrue) {
            ionicToast.show('请输入正确的身份证号码', 'top', false, 1000);
            return;
          }
        } else {
          var idInfo = getIdCardInfo($scope.user.idCardNo);
          if (!idInfo || !idInfo.isTrue) {
            ionicToast.show('请输入正确的身份证号码', 'top', false, 1000);
            return;
          }
        }


        //判断密码是否相同
        if ($scope.user.password != $scope.user.confirmPassword) {
          ionicToast.show('密码不匹配', 'top', false, 1000);
          //  angular.element('#confirmPassword').focus()
        }
        for (var idx = 0; idx < $scope.hotelImages.length; idx++) {
          var hotelImage = $scope.hotelImages[idx];
          var imageIdx = 'image' + (idx + 1);
          $scope.user[imageIdx] = hotelImage;

          $scope.user[imageIdx] = {};
          $scope.user[imageIdx].data = hotelImage;
        }


        UserService.doRegister($scope.user).then(function () {
          //注册成功回到登陆界面,进行系统登陆
          // ionicToast.showSuccess('注册成功', 'top', false, 1000);
          if ($scope.user.userType == '4') {
            $cordovaToast.showLongCenter('资料提交成功,工作人员会尽快审核. 您可以使用刚注册的用户名和密码登陆,在[通知]中看审核结果');
            //$cordovaToast.showLongCenter('资料提交成功,工作人员会尽快审核. 您可以使用刚注册的用户名和密码登陆,在[通知]中看审核结果');
          } else {
            $cordovaToast.showShortCenter('注册成功');
          }

          $state.go('signIn', {}, {reload: true});
        }, function (reason) {
          ionicToast.show(reason.message, 'top', false, 1000)
        });

      };

    }])


  .controller('ordinaryBasicInfoCtrl', function ($scope) {

  })

  .controller('HotelBasicInfoCtrl', function ($scope) {
    $scope.items = [
      'img/adam.jpg',
      'img/ben.png',
    ];
    $scope.editEnbable = false;
    $scope.toggleEnableEdit = function () {
      $scope.editEnbable = !$scope.editEnbable;
    }
  })



  /**
   * 反馈举报
   */
  .controller('FeedbackCtrl', ['$scope', '$cordovaToast', 'FeedbackService', '$cordovaToast', function ($scope, $cordovaToast, FeedbackService, $cordovaToast) {
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.items = [];
      $scope.feedback = {};

    });
    $scope.$on('$ionicView.afterEnter', function () {
      //表单验证提示
      $scope.descriptionErrorTips = {
        required: '请填写反馈信息',
        minlength: '反馈举报信息需要在10个字以上!',
      };
      $scope.submit = function () {
        for (var idx = 0; idx < $scope.items.length; idx++) {
          var imageItem = $scope.items[idx];
          var imageIdx = 'image' + (idx + 1);
          $scope.feedback[imageIdx] = {};
          $scope.feedback[imageIdx].data = imageItem;
        }
        FeedbackService.sendFeedback($scope.feedback).then(function (data) {
          $cordovaToast.showShortCenter('提交成功');
          $scope.feedback = {};
          $scope.items = [];
        }, function (err) {
          console.log(angular.toJson(err));
          $cordovaToast.showShortCenter(err.message);
        })
      }
    });

  }])

  /**
   * 反馈举报历史记录
   */
  .controller('FeedbackHistoryListCtrl', ['$scope', '$cordovaToast', 'FeedbackService', '$cordovaToast', 'AppCache', '$state',
    function ($scope, $cordovaToast, FeedbackService, $cordovaToast, AppCache, $state) {
      $scope.$on('$ionicView.beforeEnter', function () {
        $scope.historyList = [];
      });
      $scope.$on('$ionicView.afterEnter', function () {

        $scope.toFeedBackDetail = function (feedback) {
          AppCache.put('feedbackItem', feedback);
          $state.go('FeedbackDetail');
        };


        /**
         * 下拉刷新
         */
        $scope.doRefresh = function () {

          FeedbackService.getHistoryList().then(function (result) {
            $scope.historyList = result.historyList;
          }, function (error) {
            $cordovaToast.showShortCenter(error.message);
          }).finally(function () {
            $scope.$broadcast('scroll.refreshComplete');
          });
        };
        $scope.doRefresh();


      });

    }])

  /**
   * 反馈举报详情
   */
  .controller('FeedbackDetailCtrl', ['$scope', '$cordovaToast', 'FeedbackService', 'AppCache', 'AppSettings',
    function ($scope, $cordovaToast, FeedbackService, AppCache, AppSettings) {

      $scope.items = [];

      $scope.$on('$ionicView.afterEnter', function () {
        $scope.feedbackItem = AppCache.get('feedbackItem');


        for (var idx = 0; $scope.feedbackItem && idx < $scope.feedbackItem.avaiableResImages.length; idx++) {
          var image = $scope.feedbackItem.avaiableResImages[idx];
          if (image && image.id) {
            var imageUrl = AppSettings.resEndpoint + "?imageId=" + image.id;
            $scope.items.push(imageUrl);
          }
        }
      });

      $scope.$on('$ionicView.beforeLeave', function () {
        //移除缓存
        AppCache.remove('feedbackItem');

      });


    }])

  /**
   * 通知,公告
   */
  .controller('NotifycationCtrl',
    ['$scope', 'NoticeAndMessageService', '$timeout', 'AppCache', '$state', 'localStorageService', '$cordovaToast',
      function ($scope, NoticeAndMessageService, $timeout, AppCache, $state, localStorageService, $cordovaToast) {

        $scope.$on('$ionicView.beforeEnter', function () {

          $scope.doRefresh = function () {


            NoticeAndMessageService.getNoticesAndMessages().then(function (result) {
              var historicalPrivateMessages = localStorageService.get('historicalPrivateMessages');
              var historicalNoticeMessages = localStorageService.get('historicalNoticeMessages');

              $scope.privateMessags = historicalPrivateMessages ? result.privateUnreadMessages.concat(historicalPrivateMessages) : result.privateUnreadMessages;
              $scope.noticeMessages = historicalNoticeMessages ? result.notifyList.concat(historicalNoticeMessages) : result.notifyList;

            }, function (error) {
              $cordovaToast.showShortCenter(error.message);
            }).finally(function () {

              $scope.$broadcast('scroll.refreshComplete');
            });
          }

          $timeout(function () {
            $scope.doRefresh();
          }, 200);


          $scope.toPrivateMessageDetail = function (privateMessage) {
            console.log("privateMessage" + privateMessage);
            AppCache.put('privateMessage', privateMessage);

            console.log("AppCache.get('privateMessage'):" + AppCache.get('privateMessage'));

            $state.go('privateMessageDetail');
          }

          $scope.toNoticeMessageDetail = function (noticeMessage) {
            AppCache.put('noticeMessage', noticeMessage);
            $state.go('notifycationDetail');
          }
        });
      }])


  .controller('NotifycationDetailCtrl',
    ['$scope', 'AppCache', 'NoticeAndMessageService', 'localStorageService', '$ionicHistory', '$rootScope',
      function ($scope, AppCache, NoticeAndMessageService, localStorageService, $ionicHistory, $rootScope) {
        $scope.noticeMessage = AppCache.get('noticeMessage');

        $scope.$on('$ionicView.afterEnter', function () {
          if (!$scope.noticeMessage || !$scope.noticeMessage.notifyRecordId) {
            return;
          }


          NoticeAndMessageService.resetFlagNoticeReadState($scope.noticeMessage.notifyRecordId).then(function () {
            //重置成功,

            $rootScope.unReadMessageCount--;

            var historicalNoticeMessages = localStorageService.get('historicalNoticeMessages');
            $scope.noticeMessage.hasRead = true;
            if (!historicalNoticeMessages) {
              historicalNoticeMessages = [];
            }
            var isExist = false;
            for (var idx = 0; idx < historicalNoticeMessages.length; idx++) {
              var item = historicalNoticeMessages[idx];
              if (!item || !item.notifyRecordId) {
                continue;
              }
              if ($scope.noticeMessage.notifyRecordId == item.notifyRecordId) {
                isExist = true;
                break;
              }
            }
            if (!isExist) {
              historicalNoticeMessages.push($scope.noticeMessage);
            }

            localStorageService.update('historicalNoticeMessages', historicalNoticeMessages);
          }, function () {

          });

        });
        $scope.$on('$ionicView.beforeLeave', function () {
          AppCache.remove('noticeMessage');

        });

        /**
         * 从记录删除公告
         * @param privateMessage
         */
        $scope.toNoticeMessageHistory = function (privateMessage) {
          var historicalNoticeMessages = localStorageService.get('historicalNoticeMessages');
          var targetIdx = -1;
          for (var idx = 0; idx < historicalNoticeMessages.length; idx++) {
            var item = historicalNoticeMessages[idx];
            if (!item || !item.notifyRecordId) {
              continue;
            }
            if ($scope.noticeMessage.notifyRecordId == item.notifyRecordId) {
              targetIdx = idx;
              break;
            }
          }
          if (targetIdx != -1) {
            historicalNoticeMessages.splice(0, 1);
            localStorageService.update('historicalNoticeMessages', historicalNoticeMessages);
            $ionicHistory.goBack();
          }
        }

      }])
  .controller('PrivateMessageDetailCtrl',
    ['$scope', 'AppCache', 'NoticeAndMessageService', 'localStorageService', '$ionicHistory', '$rootScope',
      function ($scope, AppCache, NoticeAndMessageService, localStorageService, $ionicHistory, $rootScope) {
        $scope.privateMessage = AppCache.get('privateMessage');

        $scope.$on('$ionicView.afterEnter', function () {
          if (!$scope.privateMessage || !$scope.privateMessage.userPrivateMessageRecordId) {
            return;
          }
          if (!!$scope.privateMessage.content && $scope.privateMessage.content.indexOf('很遗憾您的旅馆申请审核未能通过,拒绝原因') != -1
            && $rootScope.hotelStatus != 'waiting') {
            $scope.showResbmitButton = true;
          } else {
            $scope.showResbmitButton = false;
          }


          NoticeAndMessageService.resetFlagPrivateMessageReadState($scope.privateMessage.userPrivateMessageRecordId).then(function () {
            //重置成功,
            $rootScope.unReadMessageCount--;

            var historicalPrivateMessages = localStorageService.get('historicalPrivateMessages');
            if (!historicalPrivateMessages) {
              historicalPrivateMessages = [];
            }
            var isExist = false;
            for (var idx = 0; idx < historicalPrivateMessages.length; idx++) {
              var item = historicalPrivateMessages[idx];
              if (!item || !item.userPrivateMessageRecordId) {
                continue;
              }
              if ($scope.privateMessage.userPrivateMessageRecordId == item.userPrivateMessageRecordId) {
                isExist = true;
                break;
              }
            }
            if (!isExist) {
              $scope.privateMessage.hasRead = true;
              historicalPrivateMessages.push($scope.privateMessage);
            }
            localStorageService.update('historicalPrivateMessages', historicalPrivateMessages);
          }, function () {

          });

        });

        /**
         * 从记录删除个人通知
         * @param privateMessage
         */
        $scope.toRemovePrivateMessageHistory = function () {
          var historicalPrivateMessages = localStorageService.get('historicalPrivateMessages');
          var targetIdx = -1;
          for (var idx = 0; idx < historicalPrivateMessages.length; idx++) {
            var item = historicalPrivateMessages[idx];
            if (!item || !item.userPrivateMessageRecordId) {
              continue;
            }
            if ($scope.privateMessage.userPrivateMessageRecordId == item.userPrivateMessageRecordId) {
              targetIdx = idx;
              break;
            }
          }
          if (targetIdx != -1) {
            historicalPrivateMessages.splice(0, 1);
            localStorageService.update('historicalPrivateMessages', historicalPrivateMessages);
            $ionicHistory.goBack();
          }
        }
        $scope.$on('$ionicView.beforeLeave', function () {
          AppCache.remove('privateMessage');

        });

      }]);



